﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lib.Db;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace TestMvc {
    public class Startup {
        public Startup (IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices (IServiceCollection services) {
            services.AddMvc ();

            services.AddScoped(typeof(UserRepository), typeof(UserRepository));
            services.AddScoped(typeof(IDbProvider), typeof(DapperDbProvider));

            services.AddSwaggerGen (c => {
                c.SwaggerDoc ("v1", new Info { Title = "My API", Version = "v1" });
            });

            services.AddOptions ();
            services.Configure<Lib.TestConfig> (Configuration.GetSection ("TestConfig"));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {

            // var data = Configuration["Data"];
            // var logger = loggerFactory.CreateLogger("Configration");
            // // logger.LogDebug("data: {0}",data);

            // var defaultConn = Configuration.GetConnectionString("DefaultConnection");
            // logger.LogInformation("DefaultConnection: {0}", defaultConn);

            // var devConn = Configuration["ConnectionStrings:dev"];
            // logger.LogInformation("devConn: {0}", devConn);

            // var testSec = Configuration.GetSection("TestSection")["TestSec1"];
            // logger.LogInformation("testSec: {0}", testSec);

            if (env.IsDevelopment ()) {
                app.UseDeveloperExceptionPage ();
            } else {
                app.UseExceptionHandler ("/Home/Error");
            }

            // 使用自定义middleware
            app.UseTestMiddelware ();

            app.UseStaticFiles ();

            app.UseSwagger ();
            app.UseSwaggerUI (opt => {
                opt.SwaggerEndpoint ("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseMvc (routes => {

                routes.MapRoute (
                    name: "default",
                    template: "{controller=api}/{action=values}");
                    // template: "{controller=Home}/{action=Index}/{id?}");
            });

        }
    }
}